import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)
import {getToken ,saveToken} from './token.js'
import {Toast, toast} from 'vant'
import router from '@/router/index.js'

const instance = axios.create({
    baseURL: 'http://toutiao.itheima.net',
    timeout: 10000,
    // headers: {'X-Custom-Header': 'foobar'}
});

instance.interceptors.request.use(
    function (config) {
        if (getToken()) {
            config.headers.Authorization='Bearer ' + getToken().token
        }
        return config
    },
    function (error) {
        return Promise.reject(error)
    }
)

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
},
   async function (error) {
    // 对响应错误做点什么
       if (error.response && error.response.status == 401) {
           if (getToken()) {
               try {
                  let res=await axios({
                      url:'http://toutiao.itheima.net/v1_0/authorizations',
                      method:'put',
                      headers: {
                        Authorization: `Bearer ${getToken().refresh_token}`
                      }
                  })
                   saveToken({
                       token:res.data.data.token,
                       refresh_token:getToken().refresh_token
                   })
                   return instance(error.config)
               }catch(err){
                Toast.success('请先登录')
                router.push('/login')
              }
           } else {
               Toast.success('请先登录')
               router.push('/login')
          }
       } else {
        //    非401错误，不做任何处理
      }
    return Promise.reject(error);
  });

export default instance